﻿using Home.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities.ViewModel;

namespace Home.WebUI.Areas.NewAdmin.Controllers
{
    public class MessageBoardController : Controller
    {
        #region 基本
        private EFDbContext db = new EFDbContext();
        private DbSet<MessageBoard> MEntity
        {
            get { return db.MessageBoards; }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
        //
        // GET: /NewAdmin/MessageBoard/

        public ActionResult Index(PagedList<MessageBoard> model, int page = 1)
        {
            //页面项数
            const int pageSize = 10;
            var list = MEntity.OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                list = list.Where(c => c.Body.Contains(model.Search));
            }
            model.Entities = list;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = MEntity.Count() };
            return View(model);
        }
        #region 删
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    var content = MEntity.Find(id);
                    //int newsNumer = MEntity.Count(n => n.PNewsId == content.Id);
                    //int newsNumer = content.News.Count();
                    //if (newsNumer > 0)
                    //{
                    //    return Content(newsNumer.ToString(CultureInfo.InvariantCulture));
                    //}
                    MEntity.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }
        #endregion
        

    }
}
